import { measurementAction, measurementFeatureType } from "../enum/measurement.enum"
import SnapUserLine3 from "../three/SnapUserLine3"
import funcUtil from "../utils/func.util"

export default class SnappablePointUpdater {
  points: any
  createPointSubscription: any
  pointer: any
  mobileCreateHackJob: any
  subscriptions: any[]
  lineSegments: any[]
  updateSnapping: (e: any) => void
  constructor(e, t, i, s) {
    ;(this.points = e),
      (this.createPointSubscription = t),
      (this.pointer = i),
      (this.mobileCreateHackJob = s),
      (this.subscriptions = []),
      (this.lineSegments = []),
      (this.updateSnapping = e => {
        this.lineSegments.length > 0 && (this.pointer.removeSnapFeatures(this, measurementFeatureType.LineSegment), (this.lineSegments.length = 0))
        for (let t = 0; t < this.points.length; t++)
          if (t !== e && t !== e - 1 && t !== e + 1 && !this.points.isStartIndex(t)) {
            const e = this.points.get(t),
              i = this.points.get(t - 1)
            this.lineSegments.push(new SnapUserLine3(i, e, measurementFeatureType.LineSegment))
          }
        this.lineSegments.length > 0 && this.pointer.addSnapFeatures(this, measurementFeatureType.LineSegment, this.lineSegments)
      })
  }
  init() {}
  dispose() {}
  activate() {
    let t = -1,
      i = -1
    const s = funcUtil.debounce(() => this.updateSnapping(this.points.length), 16)
    this.subscriptions.push(
      this.createPointSubscription(measurementAction.ADDED, s, !0),
      this.createPointSubscription(measurementAction.REMOVED, s, !0),
      this.createPointSubscription(
        measurementAction.UPDATED,
        (_e, s) => {
          s === t || (this.mobileCreateHackJob() && s === i) || (this.updateSnapping(s), (i = t), (t = s))
        },
        !0
      )
    )
  }
  deactivate() {
    this.subscriptions.forEach(e => e.cancel()),
      (this.subscriptions.length = 0),
      this.pointer.removeSnapFeatures(this, measurementFeatureType.LinePoint),
      this.pointer.removeSnapFeatures(this, measurementFeatureType.LineSegment)
  }
  beforeRender() {}
  render() {}
}
